window.onload = function () {
    var token = sessionStorage.getItem('token');
    // 刷新token
    axios.post('http://47.113.197.172:80/user/login', {
        name: sessionStorage.getItem('name'),
        password: sessionStorage.getItem('password')
    })
        .then(Response => {
            // 获取登录的用户身份和token令牌
            var newToken = Response.data.token;
            sessionStorage.setItem('token', newToken);
        })
        .catch(err => {
            console.log(err);
        })
    
    // 获取功能选择按键列表
    var funSelect = document.querySelector('.functionSelect');
    var funSelectLis = funSelect.querySelectorAll('li');

    // 获取功能详情
    var funInner = document.querySelector('.functionInner');
    var funInnerLis = funInner.querySelectorAll('.func');

    // 给每一个按键都绑定点击事件
    for (var i = 0; i < funSelectLis.length; i++) {
        // 给每个按键添加索引号，便于之后获取该元素
        funSelectLis[i].setAttribute('index', i);

        // 点击事件
        funSelectLis[i].onclick = function () {
            // 获取索引号
            var index = this.getAttribute('index');
            // 排他算法，将全部元素的小蓝块取消
            for (var i = 0; i < funSelectLis.length; i++) {
                funSelectLis[i].className = '';
            }

            if (index < funSelectLis.length) {
                funSelectLis[index].className = 'blueBlock';
            } else {
                funSelectLis[index].className = '';
            }

            // 排他算法，隐藏所有功能详情块
            for (var i = 0; i < funInnerLis.length; i++) {
                funInnerLis[i].style.display = 'none';
            }
            // 显示点击的那一个功能
            funInnerLis[index].style.display = 'block';
        }
    }

    // 编辑个人资料页面跳转
    var changeMes = document.querySelector('.changeMes');
    changeMes.onclick = function () {
        window.location.href = '../html/mesChange.html';
    }

    // axios获取用户各种信息并填入
    function updateName() {
        var baseUrl = 'http://47.113.197.172:80/user/info/';
        var id = sessionStorage.getItem('id');
        var finalUrl = baseUrl + id;

        var name = document.getElementById('name');
        var concern = document.getElementById('concern');
        var likes = document.getElementById('likes');
        var collectCount = document.getElementById('collectCount');
        var likeLabel = document.getElementById('likeLabel');
        var createAt = document.getElementById('createAt');
        var userAvatar = document.getElementById('userAvatar');

        axios.get(finalUrl)
            .then(Response => {
                // console.log(Response.data.data);
                name.innerHTML = Response.data.data.name;
                concern.innerHTML = Response.data.data.concern;
                likes.innerHTML = Response.data.data.likes;
                collectCount.innerHTML = Response.data.data.collectCount;
                // 分隔字符串
                createAt.innerHTML = Response.data.data.createAt.split('T')[0];
                userAvatar.src = Response.data.data.avatar;
            })
            .catch(err => {
                console.log(err);
            })
    }
    updateName();

    // 一些点击跳转
    concern.parentNode.onclick = function () {
        funSelectLis[5].click();
    }
    likes.parentNode.onclick = function () {
        funSelectLis[5].click();
    }
    collectCount.parentNode.onclick = function () {
        funSelectLis[4].click();
    }
    likeLabel.parentNode.onclick = function () {
        funSelectLis[5].click();
    }




    userPassageListShow();
    // 用户文章列表展示
    function userPassageListShow() {
        var baseUrl = 'http://47.113.197.172:80/user/';
        var id = sessionStorage.getItem('id');
        var finalUrl = baseUrl + id + '/articles';
        axios({
            method: 'get',
            url: finalUrl,
            headers: {
                // 'Content-Type': 'multipart/form-data',
                'Authorization': token
            }
        })
            .then(Response => {
                addInformation(Response);
                // console.log(Response.data.data[0]);
            })

            .catch(err => {
                console.log(err);
            })

    }


    // 将获取到的信息填入页面
    var userPassageList = document.getElementById('userPassageList');
    var userPassageListLi = userPassageList.querySelector('.userPassageListLi');
    function addInformation(Response) {
        for (i = 0; i < Response.data.data.length; i++) {
            // 复制一个节点
            var appendNewLi = userPassageListLi.cloneNode(true);
            // 修改节点里面的内容
            var writerName = appendNewLi.querySelector('.writerName');
            writerName.innerHTML = Response.data.data[i].authorInfo.name;
            var category = appendNewLi.querySelector('.category');
            category.innerHTML = Response.data.data[i].category;
            var passageTitle = appendNewLi.querySelector('.passageTitle');
            passageTitle.innerHTML = Response.data.data[i].title;
            var passageBrief = appendNewLi.querySelector('.passageBrief');
            passageBrief.innerHTML = Response.data.data[i].brief;
            var likeCount = appendNewLi.querySelector('.likeCount');
            likeCount.innerHTML = Response.data.data[i].likeCount;
            var commentCount = appendNewLi.querySelector('.commentCount');
            commentCount.innerHTML = Response.data.data[i].commentCount;
            var watchCount = appendNewLi.querySelector('.watchCount');
            watchCount.innerHTML = Math.round(Math.random() * 1000);

            // 根据是否点赞显示不同的图片
            var likeImg = appendNewLi.querySelector('#likeImg');
            var isLike = Response.data.data[i].isLike;
            if (isLike === 1) {
                likeImg.src = '../img/icon-like-already.png';
            }
            else {
                likeImg.src = '../img/icon-like.png';
            }

            // 判断有无封面，有显示，没有就不显示
            var passageCover = appendNewLi.querySelector('.passageCover');
            var passageCoverImg = passageCover.querySelector('img');
            if (Response.data.data[i].coverUrl == null) {
                passageCover.style.display = 'none';
            } else {
                passageCoverImg.src = Response.data.data[i].coverUrl;
            }

            // 获取文章id和作者id
            appendNewLi.id = Response.data.data[i].id;
            var writerId = Response.data.data[i].authorInfo.id;
            var likeBtn = appendNewLi.querySelector('.likeBtn');
            // 分别获取三个自定义属性（文章id，作者id，是否已经点赞），用于点击事件
            likeBtn.id = appendNewLi.id;
            likeBtn.writerId = writerId;
            likeBtn.isLike = isLike;

            var dot = appendNewLi.querySelector('.dot');
            // 点击显示编辑和删除功能
            var flag = 0;
            dot.onclick = function (event) {
                event.stopPropagation();
                if (flag == 0) {
                    this.nextElementSibling.style.display = 'block';
                    flag = 1;
                }
                else {
                    this.nextElementSibling.style.display = 'none';
                    flag = 0;
                }
            }

            // 点击编辑跳转到编辑页面
            var changePassage = appendNewLi.querySelector('.changePassage');
            changePassage.id = appendNewLi.id;
            changePassage.onclick = function (event) {
                event.stopPropagation();
                var baseUrl = 'http://47.113.197.172:80/articles/';
                var id = this.id;
                var finalUrl = baseUrl + id;
                sessionStorage.setItem('finalUrl', finalUrl);
                window.open("../html/articlesChange.html");
            }

            // 点击删除判断是否确认删除
            var deletePassage = appendNewLi.querySelector('.deletePassage');
            deletePassage.id = appendNewLi.id;
            deletePassage.onclick = function (event) {
                event.stopPropagation();
                var baseUrl = 'http://47.113.197.172:80/articles/';
                var id = this.id;
                var finalUrl = baseUrl + id;
                var confirm = window.confirm('删除文章后不可恢复，确定删除吗？');
                if (confirm) {
                    axios({
                        method: 'delete',
                        url: finalUrl,
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': token
                        }
                    })
                        .then(Response => {
                            alert('删除成功');
                            window.location.href = '../html/userMes.html';
                        })
                        .catch(err => {
                            alert('删除失败');
                        })
                }
            }

            // 将这个节点插入到ul中
            userPassageList.appendChild(appendNewLi);

            // 跳转页面
            appendNewLi.addEventListener('click', function () {
                var baseUrl = 'http://47.113.197.172:80/articles/';
                var id = this.id;
                var finalUrl = baseUrl + id;
                // 成功获取请求的文章接口
                // console.log(finalUrl);
                // 将需要调用的接口存到本地，在打开文章详情页可以跨页面调用
                sessionStorage.setItem('finalUrl', finalUrl);
                // 跳转到文章详情页
                window.open("../html/passage.html");
            })
        }

        // 点赞功能
        var likeBtnList = userPassageList.querySelectorAll('.likeBtn');
        for (i = 1; i < likeBtnList.length; i++) {
            likeBtnList[i].setAttribute('flag', 0);

            likeBtnList[i].onclick = function (event) {
                event.stopPropagation();
                if (this.isLike == 1) {
                    if (this.flag == 1) {
                        this.children[0].src = '../img/icon-like-already.png';
                        this.children[1].innerHTML++;
                        this.flag = 0;
                    } else {
                        this.children[0].src = '../img/icon-like.png';
                        this.children[1].innerHTML--;
                        this.flag = 1;
                    }
                }
                if (this.isLike == 0) {
                    if (this.flag == 0) {
                        this.children[0].src = '../img/icon-like.png';
                        this.children[1].innerHTML--;
                        this.flag = 1;
                    } else {
                        this.children[0].src = '../img/icon-like-already.png';
                        this.children[1].innerHTML++;
                        this.flag = 0;
                    }
                }

                // 对点赞或取消进行不同处理
                var baseUrl = 'http://47.113.197.172:80/articles/';
                var id = this.id;
                var finalUrl = baseUrl + id + '/likes';
                var data = JSON.stringify({
                    likedId: this.writerId
                })
                axios({
                    method: 'post',
                    url: finalUrl,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    },
                    data: data
                })
                    .then(Response => {
                        // console.log(Response.data);
                    })
                    .catch(err => {
                        console.log('点赞失败');
                    })

            }
        }
    }


    likePassageListShow();
    // 用户点赞列表展示
    function likePassageListShow() {
        var baseUrl = 'http://47.113.197.172:80/user/';
        var id = sessionStorage.getItem('id');
        var finalUrl = baseUrl + id + '/likeArticles';
        // console.log(finalUrl);
        axios({
            method: 'get',
            url: finalUrl,
            headers: {
                // 'Content-Type': 'multipart/form-data',
                'Authorization': token
            }
        })
            .then(Response => {
                addLikeListInformation(Response);
                // console.log(Response.data.data[0]);
            })

            .catch(err => {
                console.log(err);
            })
    }

    var likePassageList = document.getElementById('likePassageList');
    var likePassageListLi = likePassageList.querySelector('.likePassageListLi');
    function addLikeListInformation(Response) {
        for (i = 0; i < Response.data.data.length; i++) {
            // 复制一个节点
            var appendNewLi = likePassageListLi.cloneNode(true);
            // 修改节点里面的内容
            var writerName = appendNewLi.querySelector('.writerName');
            writerName.innerHTML = Response.data.data[i].authorInfo.name;
            var category = appendNewLi.querySelector('.category');
            category.innerHTML = Response.data.data[i].category;
            var passageTitle = appendNewLi.querySelector('.passageTitle');
            passageTitle.innerHTML = Response.data.data[i].title;
            var passageBrief = appendNewLi.querySelector('.passageBrief');
            passageBrief.innerHTML = Response.data.data[i].brief;
            var likeCount = appendNewLi.querySelector('.likeCount');
            likeCount.innerHTML = Response.data.data[i].likeCount;
            var commentCount = appendNewLi.querySelector('.commentCount');
            commentCount.innerHTML = Response.data.data[i].commentCount;
            var watchCount = appendNewLi.querySelector('.watchCount');
            watchCount.innerHTML = Math.round(Math.random() * 1000);

            // 根据是否点赞显示不同的图片
            var likeImg = appendNewLi.querySelector('#likeImg');
            var isLike = Response.data.data[i].isLike;
            if (isLike === 1) {
                likeImg.src = '../img/icon-like-already.png';
            }
            else {
                likeImg.src = '../img/icon-like.png';
            }

            // 判断有无封面，有显示，没有就不显示
            var passageCover = appendNewLi.querySelector('.passageCover');
            var passageCoverImg = passageCover.querySelector('img');
            if (Response.data.data[i].coverUrl == null) {
                passageCover.style.display = 'none';
            } else {
                passageCoverImg.src = Response.data.data[i].coverUrl;
            }

            // 获取文章id和作者id
            appendNewLi.id = Response.data.data[i].id;
            var writerId = Response.data.data[i].authorInfo.id;
            var likeBtn = appendNewLi.querySelector('.likeBtn');
            // 分别获取三个自定义属性（文章id，作者id，是否已经点赞），用于点击事件
            likeBtn.id = appendNewLi.id;
            likeBtn.writerId = writerId;
            likeBtn.isLike = isLike;

            // 将这个节点插入到ul中
            likePassageList.appendChild(appendNewLi);

            // 跳转页面
            appendNewLi.addEventListener('click', function () {
                var baseUrl = 'http://47.113.197.172:80/articles/';
                var id = this.id;
                var finalUrl = baseUrl + id;
                // 成功获取请求的文章接口
                // console.log(finalUrl);
                // 将需要调用的接口存到本地，在打开文章详情页可以跨页面调用
                sessionStorage.setItem('finalUrl', finalUrl);
                // 跳转到文章详情页
                window.open("../html/passage.html");
            })
        }

        // 点赞功能
        var likeBtnList = likePassageList.querySelectorAll('.likeBtn');
        for (i = 1; i < likeBtnList.length; i++) {
            likeBtnList[i].setAttribute('flag', 0);

            likeBtnList[i].onclick = function (event) {
                event.stopPropagation();
                if (this.isLike == 1) {
                    if (this.flag == 1) {
                        this.children[0].src = '../img/icon-like-already.png';
                        this.children[1].innerHTML++;
                        this.flag = 0;
                    } else {
                        this.children[0].src = '../img/icon-like.png';
                        this.children[1].innerHTML--;
                        this.flag = 1;
                    }
                }
                if (this.isLike == 0) {
                    if (this.flag == 0) {
                        this.children[0].src = '../img/icon-like.png';
                        this.children[1].innerHTML--;
                        this.flag = 1;
                    } else {
                        this.children[0].src = '../img/icon-like-already.png';
                        this.children[1].innerHTML++;
                        this.flag = 0;
                    }
                }

                // 对点赞或取消进行不同处理
                var baseUrl = 'http://47.113.197.172:80/articles/';
                var id = this.id;
                var finalUrl = baseUrl + id + '/likes';
                var data = JSON.stringify({
                    likedId: this.writerId
                })
                axios({
                    method: 'post',
                    url: finalUrl,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    },
                    data: data
                })
                    .then(Response => {
                        console.log(Response.data);
                    })
                    .catch(err => {
                        console.log('点赞失败');
                    })

            }
        }
    }







}